package com.jufanshare.myblog.common.util;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @功能：
 * @开发者： 余志强
 * @编写时间： 2019/3/20 09:39
 */
public class OkHttpUtil {
    private final static Log log= LogFactory.getLog(OkHttpUtil.class);
    private static OkHttpClient okHttpClient= new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10,TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .build();

    /**
     * get请求，
     * @param url
     */
    public static String doGet(String url){
        Request request = new Request.Builder()
                .url(url)//请求的url
                .get()//设置请求方式，get()/post()  查看Builder()方法知，在构建时默认设置请求方式为GET
                .build(); //构建一个请求Request对象
        return getResult(request);
    }
    /**
     * get请求，
     * @param url
     * @param async 是否开启异步 false ： 同步
     * @return 无返回值
     */
    public static void doGet(final String url,boolean async){
        if(!async){
            doGet(url);
        } else {
            Request request = new Request.Builder()
                    .url(url)//请求的url
                    .get()//设置请求方式，get()/post()  查看Builder()方法知，在构建时默认设置请求方式为GET
                    .build(); //构建一个请求Request对象
            //创建/Call
            Call call = okHttpClient.newCall(request);
            //加入队列 异步操作
            call.enqueue(new OkHttpCallBack());
        }
    }

    /**
     * Body方式POST请求
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map<String,String> params) {
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : params.keySet()) {
            //追加表单信息
            builder.add(key, params.get(key));
        }
        RequestBody body = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return getResult(request);
    }

    /**
     * 是否异步模式
     * @param url
     * @param params
     * @param async false 同步
     */
    public static void doPost(String url, Map<String,String> params,boolean async) {
        if(!async){
            doPost(url,params);
        }else {
            FormBody.Builder builder = new FormBody.Builder();
            for (String key : params.keySet()) {
                //追加表单信息
                builder.add(key, params.get(key));
            }
            RequestBody body = builder.build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            okHttpClient.newCall(request).enqueue(new OkHttpCallBack());
        }
    }

    /**
     * JSON方式POST请求【传入对象】
     * @param url
     * @param param
     * @return
     */
    public static String doPost(String url, Object param) {
        String jsonString = JSON.toJSONString(param);
        //MediaType  设置Content-Type 标头中包含的媒体类型值
        RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                ,jsonString);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return getResult(request);
    }
    public static void doPost(String url, Object param,boolean async) {
        if(!async){
            doPost(url, param);
        }else {
            String jsonString = JSON.toJSONString(param);
            //MediaType  设置Content-Type 标头中包含的媒体类型值
            RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                    ,jsonString);
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            okHttpClient.newCall(request).enqueue(new OkHttpCallBack());
        }
    }

    /**
     * JSON方式POST请求【直接传入json字符串】
     * @param url
     * @param param
     * @return
     */
    public static String doPost(String url, String param) {
        //MediaType  设置Content-Type 标头中包含的媒体类型值
        RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                ,param);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return getResult(request);
    }
    public static void doPost(String url, String param,boolean async) {
        if(!async){
            doPost(url,param);
        }else {
            //MediaType  设置Content-Type 标头中包含的媒体类型值
            RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                    ,param);
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            okHttpClient.newCall(request).enqueue(new OkHttpCallBack());
        }
    }

    /**
     * 发起请求，获取结果
     * @param request
     * @return
     */
    private static String getResult(Request request){
        try {
            Response response = okHttpClient.newCall(request).execute();
            if(response.isSuccessful()){
                return response.body().string();
            }else {
                return "请求失败,错误码："+response.code()+"\t信息："+response.message();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "请求结束：错误为\t"+e.getMessage();
        }
    }
    private static class OkHttpCallBack implements Callback{

        @Override
        public void onFailure(Call call, IOException e) {
            log.error("请求错误【】"+call.toString());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            log.info("请求成功：\t"+response.body().toString());
        }
    }
}
